<template>
  <div>
    <Head />
    <div class="orders-area">
      <div class="container">
        <div class="row">
          <div class="Breadcrumb">
            <el-page-header title="返回" content="我的订单" @back="goBack" />
          </div>
          <div class="table">
            <el-table
              ref="multipleTable"
              v-loading="loading"
              :data="tableData"
              style="width: 1140px; border-radius: 10px; margin-top: 30px;"
              :header-cell-style="{background: '#faf6f6'}"
              :row-style="{background: '#faf6f6'}"
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                align="center"
                type="selection"
              />
              <el-table-column
                align="center"
                fixed="left"
                label="下单时间"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.gmtCreate }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                fixed="right"
                label="书名"
              >
                <template slot-scope="scope">
                  <span style="font-weight: bold; color: #000">{{ scope.row.bookName }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                fixed="left"
                label="封面"
              >
                <template slot-scope="scope">
                  <img
                    :src="scope.row.cover"
                    :style="{ width: '140px', height: '140px', borderRadius: '10px'} "
                  >
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                fixed="right"
                label="总计"
              >
                <template slot-scope="scope">
                  <span style="color: red; font-weight: bold; font-size: 18px">￥ {{ scope.row.total }} / {{ scope.row.bookNumber }} 本</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                fixed="right"
                label="订单状态"
              >
                <template slot-scope="scope">
                  <span style="font-weight: bold; color: #000">{{ scope.row.status }}</span>
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                fixed="right"
                label="操作"
              >
                <!-- width="180" -->
                <template slot-scope="scoped" style="color: #337ab7">
                  <router-link
                    v-if="scoped.row.status === '已支付'"
                    :to="{
                      path: '/bookDetails',
                      name: 'bookDetails',
                      query: {
                        id: scoped.row.bookId,
                      }
                    }"
                  >查看</router-link>
                  <el-link v-else :underline="false" @click="updateOrder(scoped.row.orderId)">购买</el-link>
                  <br>
                  <el-link :underline="false" @click="deleteOrder(scoped.row.orderId)">删除</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="btn">
            <el-button style="margin: 30px 20px" type="danger" @click="deleteOrders(), clickHandler($event)">删除选中订单</el-button>
            <el-button style="margin: 30px 20px" @click="updateOrders(), clickHandler($event)">支付选中订单</el-button>
          </div>
        </div>
      </div>
    </div>
    <Foot />
  </div>
</template>

<script>
import userApi from '@/api/user'
import Head from '@/views/user/component/Head'
import Foot from '@/views/user/component/Footer'

export default {
  components: { Head, Foot },
  inject: ['reload'],
  data() {
    return {
      tableData: [],
      user: false,
      userId: 0,
      loading: true
    }
  },
  created:
    async function() {
      this.userId = this.$store.getters.token
      await this.initData()
    },
  methods: {
    // 勾选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getOrder() {
      return new Promise(resolve => {
        userApi.getAllOrder().then(resp => {
          resolve(resp.data.data)
        }, err => {
          console.log(err)
        })
      })
    },
    // async+await  同步请求  避免axios嵌套
    async initData() {
      this.loading = true
      const orderItems = await this.getOrder()
      this.tableData = orderItems['ok'].concat(orderItems['error'])
      this.loading = false
    },
    updateOrder(item) {
      userApi.orderUpdateStatus(item).then(resp => {
        resp.data.code === 200 ? this.$message.success('支付成功！') : this.$message.error('支付失败！')
        this.initData()
      })
    },
    async updateOrders() {
      var order = []
      this.multipleSelection.forEach(data => {
        order.push(data.orderId)
      })
      order.forEach(item => {
        userApi.orderUpdateStatus(item).then(resp => {

        })
      })
      this.$message.success('支付成功！')
      this.initData()
      this.$message({
        message: '支付成功！',
        type: 'success',
        duration: 2000
      })
    },
    reloadIndex() {
      this.reload()
    },
    deleteOrder(item) {
      userApi.deleteOrders(new Array(item)).then(resp => {
        resp.data.code === 200 ? this.$message.success('删除成功！') : this.$message.error('删除失败！')
        this.initData()
      })
    },
    deleteOrders() {
      var order = []
      this.multipleSelection.forEach(data => {
        order.push(data.orderId)
      })
      userApi.deleteOrders(order).then(resp => {
        console.log(resp)
        resp.data.code === 200 && this.$message.success('删除成功！')
        this.initData()
      }, err => {
        this.$message.danger('删除失败！')
        console.log(err)
      })
    },
    goBack() {
      this.$router.push({ path: '/' })
    }
  }

}
</script>

<style scoped>
.container {
    width: 100%;
    max-width: 1140px;
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}
.row {
  display: flex;
  justify-content: space-between;
}
.orders-area {
    margin-top: 30px;
    margin-bottom: 30px;
}
.orders-area .row {
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: flex-end;
}
.orders-area .Breadcrumb {
  display: flex;
  width: 100%;
  justify-content: flex-start;
}
.orders-area .row .btn {
  display: flex;
  width: 100%;
  justify-content: space-between;
}
</style>
